#include "SeqList.h"

void SLInit(SL* ps)
{
    assert(ps);//断言一下指针是否为空
    ps->Data = NULL;
    ps->size = 0;
    ps->capacity = 0;
}

void SLPrintf(SL* ps)
{
    assert(ps);
    for(int i = 0; i < ps->size; i++)
    {
        printf("%d ",ps->Data[i]);
    }
    printf("\n");
}


int SLFind(SL* ps,SLDataType x)
{
    assert(ps);
    for(int i = 0; i < ps->size; i++)
    {
        if(ps->Data[i] == x)
        {
            return i;
        }
    }
    return -1;
}

static void SLCheckCapacity(SL* ps)
{
    assert(ps);
    if( ps->size == ps->capacity )//扩容
    {
        if( ps->capacity == 0 )
        {
            ps->Data = (SLDataType*)malloc(sizeof(SLDataType) * 4);
            ps->capacity = 4;
        }
        else
        {
            SLDataType* tmp = (SLDataType*)realloc(ps->Data,sizeof(SLDataType) * 2 * ps->capacity);
            ps->Data = tmp;
            ps->capacity *= 2;
        }

        if(ps->Data == NULL)//扩容失败，直接终止掉程序
        {
            perror("SLCheckCapacity failed");
            exit(-1);
        }
    }
}

void SLPushBack(SL* ps,SLDataType x)
{
    assert(ps);
    SLCheckCapacity(ps);//检查容量，是否需要扩容
    ps->Data[ps->size] = x;
    ps->size++;//增加数据个数
}

void SLPopBack(SL* ps)
{
    assert(ps);
    assert(ps->size > 0);
    ps->size--;
}

void SLPushFront(SL* ps,SLDataType x)
{
    assert(ps);
    SLCheckCapacity(ps);
    int end = ps->size - 1;

    while(end >= 0)//重后往前挪
    {
        ps->Data[end + 1] = ps->Data[end];
        end--;
    }
    ps->Data[0] = x;
    ps->size++;
}

void SLPopFront(SL* ps)
{
    assert(ps);
    assert(ps->size > 0);
    int pos = 0;
    while(pos < ps->size)
    {
        ps->Data[pos] = ps->Data[pos + 1];
        pos++;
    }
    ps->size--;
}


void SLInsert(SL* ps,int pos,SLDataType x)
{
    assert(ps);
    assert(pos <= ps->size && pos >= 0);
    SLCheckCapacity(ps);

    int end = ps->size - 1;
    while(end >= pos)
    {
        ps->Data[end + 1] = ps->Data[end];
        end--;
    }

    ps->Data[pos] = x;
    ps->size++;
}

void SLErase(SL* ps,int pos)
{
    assert(ps);
    assert(pos < ps->size && ps->size > 0);

    int end = ps->size;
	int begin = pos;
	while (begin < end)
	{
		ps->Data[begin] = ps->Data[begin + 1];
		begin++;
	}
    ps->size--;
}


void SLDestroy(SL* ps)
{
    assert(ps);
    free(ps->Data);
    ps->Data = NULL;
    ps->capacity = 0;
    ps->size = 0;
}

